package com.shamoa.springbootredis.config;

import com.shamoa.springbootredis.demos.exMessageListener.RedisKeyExpirationListener;
import com.shamoa.springbootredis.demos.messageListener.RedisMessageListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import javax.annotation.Resource;

/**
 * @author zy
 * @version 1.0
 * @date 2024/3/24 15:00
 * @description 消息监听配置
 **/
@Configuration
public class RedisListenerConfig {

    @Resource
    private RedisMessageListener redisMessageListener;

    /**
     * 消息侦听器容器
     *
     * @param factory
     * @return
     */
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory factory,
                                                                       MessageListenerAdapter messageListenerAdapter) {
        RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
        listenerContainer.setConnectionFactory(factory);
        listenerContainer.addMessageListener(messageListenerAdapter, new ChannelTopic("redis-channel"));
        return listenerContainer;
    }

    /**
     * 消息监听适配器
     *
     * @return
     */
    @Bean
    public MessageListenerAdapter messageListener() {
        return new MessageListenerAdapter(redisMessageListener);
    }

    /**
     * 消息过期监听
     *
     * @param listenerContainer
     * @return
     */
    @Bean
    public KeyExpirationEventMessageListener redisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        return new RedisKeyExpirationListener(listenerContainer);
    }

}
